package com.p2p.common.utils;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.p2p.common.constants.Message;
import com.p2p.common.constants.ParamKey;

/**
 * Created by lizhuolun on 2016/9/1.
 */
public final class ResponseUtil {

    private ResponseUtil() {
    }

    private static final Logger logger = LoggerFactory.getLogger(ResponseUtil.class);

    public static void write(HttpServletRequest req, HttpServletResponse res, int code, String msg) {
        res.setHeader("Cache-Control", "no-cache");
        res.setContentType("text/html;charset=utf-8");
        res.setCharacterEncoding("UTF-8");
        String callback = req.getParameter(ParamKey.In.callback);
        try {
            String json = JSONUtil.beanToJson(new Message(code, msg));
            PrintWriter printWriter = res.getWriter();
            if (null != callback && callback.length() > 0) {
                printWriter.write(callback + "(" + json + ")");
            } else {
                printWriter.write(json);
            }
            printWriter.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
